package com.accenture.portal.controller.questionnaire;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.aspectj.apache.bcel.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.accenture.portal.model.Article;
import com.accenture.portal.model.User;
import com.accenture.portal.model.questionnaire.Question;
import com.accenture.portal.model.questionnaire.Questionnaire;
import com.accenture.portal.service.questionnaire.AnswerService;
import com.accenture.portal.service.questionnaire.OptionService;
import com.accenture.portal.service.questionnaire.QuestionService;
import com.accenture.portal.service.questionnaire.QuestionnaireService;

@Controller
public class QuestionnaireController {
	@Autowired
	QuestionnaireService questionnaireService;
	@Autowired
	QuestionService questionService; 
	@Autowired
	OptionService optionService;
	@Autowired
	AnswerService answerService;
	
	/**分页显示所有问卷列表
	 * @param number
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "allQuestionnaire.action")
	public String getallQuestionnaire(@RequestParam("number") Integer number,
			HttpServletRequest request, Model model) {
		Integer page = 5;//每页显示条数
		Integer total = questionnaireService.getTotalQuestionnaire();//总条数
//		Integer total=16;
		Integer count = total / page;
		if (total % page != 0) {  
			count++;              //总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		
		if (number < 1) {//当前最小页数限制
			number = 1;
		} else if (number > count) {
			number = count;//当前最大页数限制
		}
		
		List<Questionnaire> questionnaireList = questionnaireService.getAllQuestionnaire((number - 1)
				* page, page);//取一页的数据
		request.getSession().setAttribute("number", number);
		model.addAttribute("questionnaireList", questionnaireList);
		request.getSession().setAttribute("count", count);

		return "questionnaire/allQuestionnaire";
	}
	
	/**后台管理搜索功能
	 * @param number
	 * @param searchType
	 * @param searchWords1
	 * @param dateString
	 * @param status
	 * @param category
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "searchQuestionnaire.action")
	public String searchQuestionnaire(
			@RequestParam("number") Integer number,//当前页码
			@RequestParam("searchType") Integer searchType,  //搜索类型
			@RequestParam("searchWords") String searchWords1,//输入的搜索关键字
			@RequestParam("dateString") String dateString,//输入的日期，为String型，下面会转为Date
			@RequestParam("status") Integer status,//问卷状态
			@RequestParam("category") Integer category,//问卷种类
			HttpServletRequest request, Model model) {
		String searchWords="%"+searchWords1+"%";
		Integer page = 5;//每页显示条数
		Integer total=0;//总问卷条数
		Integer count=0;//显示的总页数
		List<Questionnaire> questionnaireList = new ArrayList<Questionnaire>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date date=new Date();
		try {
			date = sdf.parse(dateString);//日期转为Date型
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//筛选条件
		switch (searchType) {
		case 0:  //获取全部问卷
			total = questionnaireService.getTotalQuestionnaire();//总条数
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.getAllQuestionnaire((number - 1)* page, page);//取一页的数据
		    break;
		case 1:  //按问卷名搜索
			total = questionnaireService.searchQuestionnaireByNameCount(searchWords);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByName(searchWords, (number - 1)* page,page);
		    break;
		case 2:  //按问卷状态（打开/关闭）搜索
			total = questionnaireService.searchQuestionnaireByStatusCount(status);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByStatus(status, (number - 1)* page,page);
		    break;
		case 3:  //按问卷类型搜索
			total = questionnaireService.searchQuestionnaireByCategoryCount(category);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByCategory(category, (number - 1)* page,page);
		    break;
		case 4:  //按问卷包含的问题名搜索
			total = questionnaireService.searchQuestionnaireByQuestionCount(searchWords);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByQuestion(searchWords, (number - 1)* page,page);
		    break;
		case 5:  //按问创建问卷的人的名字 搜索
			total = questionnaireService.searchQuestionnaireByCreaterCount(searchWords);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByCreater(searchWords, (number - 1)* page,page);
		    break;
		case 6: //按问卷名创建时间搜索
			total = questionnaireService.searchQuestionnaireByCreateTimeCount(date);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByCreateTime(date, (number - 1)* page,page);
		    break;
		case 7:  //按问卷失效日期搜索
			total = questionnaireService.searchQuestionnaireByDeadlineCount(date);
			count=getCount(page,total, count);
			number=getNumber(number, count);
			questionnaireList = questionnaireService.searchQuestionnaireByDeadline(date, (number - 1)* page,page);
		    break;
		default:
		    System.out.println("searchType is not right！！");
		}

		model.addAttribute("questionnaireList", questionnaireList);
		request.getSession().setAttribute("count", count);
		request.getSession().setAttribute("number", number);
		request.getSession().setAttribute("searchType", searchType);//保存搜索类型，
		request.getSession().setAttribute("searchWords", searchWords1);
		request.getSession().setAttribute("dateString", dateString);
		request.getSession().setAttribute("status", status);
		request.getSession().setAttribute("category", category);
		return "questionnaire/allQuestionnaire";
	}
	
	/**计算number的工具方法
	 * @param number
	 * @param count
	 * @return
	 */
	public Integer getNumber(Integer number,Integer count){
		if (number < 1) {//当前最小页数限制
			number = 1;
		} else if (number > count) {
			number = count;//当前最大页数限制
		}
		return number;
	}
	
	/**计算count的工具方法
	 * @param page
	 * @param total
	 * @param count
	 * @return
	 */
	public Integer getCount(Integer page,Integer total,Integer count){
		count = total / page;
		if (total % page != 0) {  
			count++;              //总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		return count;
	}
	
	/**分类显示问卷
	 * @param number
	 * @param category
	 * @param request
	 * @param model
	 * @return
	 */
	/*@RequestMapping(value = "allQuestionnaireByCategory.action")
	public String getAllQuestionnaireByCategory(@RequestParam("number") Integer number,@RequestParam("category") Integer category,
			HttpServletRequest request, Model model) {
		Integer page = 5;//每页显示条数
		Integer total = questionnaireService.getTotalQuestionnaireByCategory(category);//总条数
//		Integer total=16;
		Integer count = total / page;
		if (total % page != 0) {  
			count++;              //总页数
		}
		
		if(count==0){ 
			count=1;//数据库没有数据时显示在总共1页
		}
		
		if (number < 1) {//当前最小页数限制
			number = 1;
		} else if (number > count) {
			number = count;//当前最大页数限制
		}
		
		List<Questionnaire> questionnaireList = questionnaireService.getAllQuestionnaireByCategory((number - 1)
				* page, page,category);//取一页的数据
		request.getSession().setAttribute("number", number);
		request.getSession().setAttribute("category", category);
		model.addAttribute("questionnaireList", questionnaireList);
		request.getSession().setAttribute("count", count);

		return "questionnaire/allQuestionnaireByCategory";
	}*/
	
	/**添加问卷
	 * @param questionnaireName
	 * @param questionnaireStatus
	 * @param questionnaireCategory
	 * @param questionnaireDeadlineString
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "addQuestionnaire.action", method = RequestMethod.POST)
	public String addQuestionnaire(@RequestParam("questionnaireName") String questionnaireName,
			@RequestParam("questionnaireStatus") Boolean questionnaireStatus,
			@RequestParam("questionnaireCategory") Integer questionnaireCategory,
			@RequestParam("questionnaireDeadline") String questionnaireDeadlineString,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws UnsupportedEncodingException {
//		questionnaire.setQuestionnaireDeadline((Date)questionnaire.getQuestionnaireDeadline());
//		SimpleDateFormat questionnaireDeadline = new SimpleDateFormat(questionnaire.getQuestionnaireDeadline());  
//	    Date date = sdf.parse(dateString);
//		System.out.println(questionnaire.getQuestionnaireDeadline());
//		String dateString = "2012-12-06 "; 
		Questionnaire questionnaire=new Questionnaire();
//		Date questionnaireDeadline = null;
		try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		Date questionnaireDeadline = sdf.parse(questionnaireDeadlineString);//日期转为Date型
		questionnaire.setQuestionnaireDeadline(questionnaireDeadline);
		}  
		catch (ParseException e)
		{System.out.println(e.getMessage());} 
		
		questionnaire.setQuestionnaireName(questionnaireName);
		questionnaire.setQuestionnaireStatus(questionnaireStatus);
		questionnaire.setQuestionnaireCategory(questionnaireCategory);
		Integer questionnaireCreater=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		questionnaire.setQuestionnaireCreater(questionnaireCreater);
		
		questionnaireService.addQuestionnaire(questionnaire);
		Integer count = (Integer) request.getSession().getAttribute("count");//获取当前页
		return "redirect:fusionSearchQuestionnaire.action?number="+count+"&questionnaireName=&questionnaireStatus=2&questionnaireCategory=0&timeStart=&timeEnd=";//返回并刷新当前页
	}
	
	
	/**跳转添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toAddQuestionnaire.action", method = RequestMethod.GET)
	public String toAddQuestionnaire(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "questionnaire/addQuestionnaire";
	}
	
	
	/*@RequestMapping(value = "deleteQuestionnaire.action", method = RequestMethod.GET)
	public String deleteQuestionnaire(@RequestParam("questionnaireId") Integer questionnaireId,
			HttpServletRequest request,HttpServletResponse response, Model model) {
		questionnaireService.deleteQuestionnaire(questionnaireId);
		return "redirect:allQuestionnaire.action?number=1";
	}*/
	
	/**删除单个问卷
	 * @param questionnaireId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "deleteQuestionnaire.action", method = RequestMethod.GET)
	public String deleteQuestionnaire(@RequestParam("questionnaireId") Integer questionnaireId,
			HttpServletRequest request,HttpServletResponse response, Model model) {
		List<Question> questionListTemp = questionService.getQuestionByQuestionnaire(questionnaireId);
		for(Integer i=0;i<questionListTemp.size();i++){
			optionService.deleteOptionByQuestion(questionListTemp.get(i).getQuestionId());
		}
		questionService.deleteQuestionByQuestionnaire(questionnaireId);
		answerService.deleteAnswerByQuestionnaire(questionnaireId);
		questionnaireService.deleteQuestionnaire(questionnaireId);
		return "redirect:fusionSearchQuestionnaire.action?number=1&questionnaireName=&questionnaireStatus=2&questionnaireCategory=0&timeStart=&timeEnd=";
	}
	
	/**删除多个问卷
	 * @param questionnaireIdList
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "deleteQuestionnaireMulti.action", method = RequestMethod.GET)
	public void deleteQuestionnaireMulti(@RequestParam("questionnaireIdList") String questionnaireIdList,
			HttpServletRequest request,HttpServletResponse response, Model model) {
		String questionnaireMulti[] = questionnaireIdList.split(",");//分割出所有问卷id
//		articleService.markAsReadMulti(user_id, markMulti);
		for (Integer i = 0; i < questionnaireMulti.length; i++) {
			Integer questionnaireId = Integer.valueOf(questionnaireMulti[i]);
			List<Question> questionListTemp = questionService.getQuestionByQuestionnaire(questionnaireId);
			for(Integer j=0;j<questionListTemp.size();j++){
				optionService.deleteOptionByQuestion(questionListTemp.get(j).getQuestionId());
			}
			questionService.deleteQuestionByQuestionnaire(questionnaireId);
			answerService.deleteAnswerByQuestionnaire(questionnaireId);
			questionnaireService.deleteQuestionnaire(questionnaireId);
		}
	}
	
	/**编辑问卷
	 * @param questionnaire
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@RequestMapping(value = "editQuestionnaire.action", method = RequestMethod.POST)
	public String editQuestionnaire(@ModelAttribute Questionnaire questionnaire,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws UnsupportedEncodingException {
		questionnaire.setQuestionnaireId((Integer)request.getSession().getAttribute("questionnaireId"));//获取当前编辑的文章id
		Integer questionnaireUpdater=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		questionnaire.setQuestionnaireUpdater(questionnaireUpdater);
		questionnaireService.editQuestionnaire(questionnaire);
		return "redirect:fusionSearchQuestionnaire.action?number=1&questionnaireName=&questionnaireStatus=2&questionnaireCategory=0&timeStart=&timeEnd=";//返回并刷新首页
	}*/
	
	/**编辑问卷
	 * @param questionnaire
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "editQuestionnaire.action", method = RequestMethod.POST)
	public String editQuestionnaire(@RequestParam("questionnaireName") String questionnaireName,
			@RequestParam("questionnaireStatus") Boolean questionnaireStatus,
			@RequestParam("questionnaireCategory") Integer questionnaireCategory,
			@RequestParam("questionnaireDeadline") String questionnaireDeadlineString,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws UnsupportedEncodingException {
		Questionnaire questionnaire=new Questionnaire();
		try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		Date questionnaireDeadline = sdf.parse(questionnaireDeadlineString);//日期转为Date型
		questionnaire.setQuestionnaireDeadline(questionnaireDeadline);
		}  
		catch (ParseException e)
		{System.out.println(e.getMessage());} 
		
		questionnaire.setQuestionnaireName(questionnaireName);
		questionnaire.setQuestionnaireStatus(questionnaireStatus);
		questionnaire.setQuestionnaireCategory(questionnaireCategory);
		questionnaire.setQuestionnaireId((Integer)request.getSession().getAttribute("questionnaireId"));//获取当前编辑的文章id
		Integer questionnaireUpdater=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		questionnaire.setQuestionnaireUpdater(questionnaireUpdater);
		
		questionnaireService.editQuestionnaire(questionnaire);
//		model.addAttribute("questionnaireLast", questionnaire);
		return "redirect:fusionSearchQuestionnaire.action?number=1&questionnaireName=&questionnaireStatus=2&questionnaireCategory=0&timeStart=&timeEnd=";//返回并刷新当前页
		
		
		
		
//		questionnaire.setQuestionnaireId((Integer)request.getSession().getAttribute("questionnaireId"));//获取当前编辑的文章id
//		Integer questionnaireUpdater=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
//		questionnaire.setQuestionnaireUpdater(questionnaireUpdater);
//		questionnaireService.editQuestionnaire(questionnaire);
//		return "redirect:allQuestionnaire.action?number=1";//返回并刷新首页
	}
	/**跳转编辑问卷页面
	 * @param questionnaireId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toEditQuestionnaire.action", method = RequestMethod.GET)
	public void toEditQuestionnaire(@RequestParam("questionnaireId") Integer questionnaireId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Questionnaire questionnaire = questionnaireService.getQuestionnaireById(questionnaireId);
//		String questionnaireDeadlineThis=questionnaire.getQuestionnaireDeadline().toString();
		Date questionnaireDeadline=questionnaire.getQuestionnaireDeadline();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String questionnaireDeadlineLast = sdf.format(questionnaireDeadline);
		
        request.getSession().setAttribute("questionnaireDeadlineLast", questionnaireDeadlineLast);
		request.getSession().setAttribute("questionnaireId", questionnaireId);
		model.addAttribute("questionnaireLast", questionnaire);
		
		
		Map<String,Object> mapMulti=new HashMap<String, Object>();//封装为map发送到前台
		mapMulti.put("questionnaireDeadlineLast",questionnaireDeadlineLast);
		mapMulti.put("questionnaireLast", questionnaire);
		JSONObject json = JSONObject.fromObject(mapMulti);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
//		return "questionnaire/editQuestionnaire";
	}
	
	/**前台页面的问卷列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "openQuestionnaireListFront.action")
	public String openQuestionnaireListFront(HttpServletRequest request,HttpServletResponse response,Model model) {
		return "questionnaire/questionnaireListFront";
	}
	
	/**融合搜索
	 * @param questionnaireName
	 * @param questionnaireStatus
	 * @param questionnaireCategory
	 * @param timeStart
	 * @param timeEnd
	 * @param number
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "fusionSearchQuestionnaire.action")
	public String fusionSearchQuestionnaire(
			@RequestParam("questionnaireName") String questionnaireNameTemp,
			@RequestParam("questionnaireStatus") String questionnaireStatusTemp,
			@RequestParam("questionnaireCategory") String questionnaireCategoryTemp,
			@RequestParam("timeStart") String timeStartString,
			@RequestParam("timeEnd") String timeEndString,
			@RequestParam("number") Integer number,
			HttpServletRequest request, Model model) {
		String questionnaireName="%"+questionnaireNameTemp+"%";
		String questionnaireStatus;
		String questionnaireCategory;
		if(questionnaireStatusTemp.equals("2")){
			 questionnaireStatus="%%";
		}
		else{
			questionnaireStatus="%"+questionnaireStatusTemp+"%";
		}
		
		if(questionnaireCategoryTemp.equals("0")){
			questionnaireCategory="%%";
		}else{
			questionnaireCategory="%"+questionnaireCategoryTemp+"%";
		}
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date timeStart=new Date();
		Date timeEnd=new Date();
		if(timeStartString==null || timeStartString==""){
//			timeStart=new Date(2010,00,00);
			try {
				timeStart = sdf.parse("1970-01-01");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
			
			try {
				timeStart = sdf.parse(timeStartString);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		String woDate=sdf.format(timeStart);
		System.out.println(woDate);
		
		
		if(timeEndString==null || timeEndString==""){
//			timeEnd=new Date(2020,00,00);
			try {
				timeEnd = sdf.parse("2030-01-01");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
			try {
				timeEnd = sdf.parse(timeEndString);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		/*String woDateEnd=sdf.format(timeEnd);
		System.out.println(woDateEnd);*/
		Integer page = 6;//每页显示条数
		Integer total=0;//总条数
		Integer count=0;//总页数
		total = questionnaireService.fusionSearchQuestionnaireCount(questionnaireName, questionnaireStatus, questionnaireCategory, timeStart, timeEnd);//总条数
		count=getCount(page,total, count);
		number=getNumber(number, count);
		List<Questionnaire> questionnaireList = questionnaireService.fusionSearchQuestionnaire(questionnaireName, questionnaireStatus, questionnaireCategory, timeStart, timeEnd, (number - 1)* page, page);//取一页的数据
		model.addAttribute("questionnaireList", questionnaireList);
		request.getSession().setAttribute("count", count);
		request.getSession().setAttribute("number", number);
		request.getSession().setAttribute("questionnaireName", questionnaireNameTemp);
		request.getSession().setAttribute("questionnaireStatus", questionnaireStatusTemp);
		request.getSession().setAttribute("questionnaireCategory", questionnaireCategoryTemp);
		request.getSession().setAttribute("timeStart", timeStartString);
		request.getSession().setAttribute("timeEnd", timeEndString);
		return "questionnaire/allQuestionnaire";
	}
}
